package framework.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 * @class JSONReader
 * @author Lasse Benninga
 * @version 1.0
 */
public class JSONReader {
	
	/*
	 * Check for Gameconfig file (corresponding to the gameName), if it hasn't
	 * been created yet: create JSON-file with gameValues. If the Gameconfig
	 * file exists, parse the data.
	 */
	public static JSONObject getGameSettings(String gameName) throws Exception {
		
		File gameFile = new File("game_data\\" + gameName);
		JSONParser parser = new JSONParser();
		JSONObject jsonObject = null;

		if(gameFile.isFile()) {
			Object oObj;
//			try {
			oObj = parser.parse(
				new BufferedReader(new FileReader("game_data\\" + gameName))
			);
			JSONObject nJsonObject = (JSONObject) oObj;
			jsonObject = nJsonObject;
//			} catch (IOException | ParseException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
		}
		return jsonObject;
	}

	public static void setGameSettings(String gameName, JSONObject jsonObject) throws IOException{
		FileWriter file = new FileWriter("game_data\\" + gameName);
		file.write(jsonObject.toJSONString());
		file.close();
	}

	public static void readGameSettings(String gameName) {
		String gameType = "";
		int width = 0;
		int height = 0;
		JSONParser parser = new JSONParser();
		try {

			Object obj = parser.parse(new BufferedReader(new FileReader(
					"game_data\\" + gameName)));

			JSONObject jsonObject = (JSONObject) obj;
			gameType = (String) jsonObject.get("gametype");
			JSONArray msg = (JSONArray) jsonObject.get("board");
			Iterator<Integer> iterator = msg.iterator();
			while (iterator.hasNext()) {
				width = iterator.next();
				height = iterator.next();
			}
		} catch (IOException | ParseException e) {
			e.printStackTrace();
		}finally{
			// Hier moet je dus de waardes gebruiken.
	}
	}

	
	
	public static JSONObject setGameSettings(String gameType, int height, int width){
		JSONObject obj = new JSONObject();
		obj.put("gametype", gameType);
		
		JSONArray list = new JSONArray();
		list.add(new Integer(height));
		list.add(new Integer(width));
		obj.put("board", list);
		return  obj;
	}
}
